package com.examinantsdk.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.examinantsdk.base.view.LoadingDialog;
import com.google.gson.JsonSyntaxException;

import java.io.IOException;
import java.net.ConnectException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * Created by wjy.
 * Date: 2019/11/22
 * Time: 15:48
 * Describe: ${describe}
 */
public abstract class NetSubscribe<T> implements Observer<T> {

    private Activity mContext;
    private LoadingDialog loadingDialog;
    private boolean isShow;

    public NetSubscribe(Activity mContext, boolean isShow) {
        this.mContext = mContext;
        this.isShow = isShow;
    }

    @Override
    public void onNext(T value) {
        onSuccess(value);
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onComplete() {

    }

    @SuppressLint("BinaryOperationInTimber")
    @Override
    public void onError(Throwable e) {
        LogUtils.d("Api=> onError:" + e);
        String errorMsg = e.getMessage();
        if (TextUtils.equals(errorMsg, Constants.TOKEN_INVALID)) { //token过期
            MyApplication.invalidLogin();
            if (BaseAppManager.getInstance().getFrontActivity()!=null&&BaseAppManager.getInstance().getFrontActivity().getLocalClassName()!=null){
                if (!"ui.login.SmsLoginUI".equals(BaseAppManager.getInstance().getFrontActivity().getLocalClassName())) {
                    MyApplication.checkLogin(BaseAppManager.getInstance().getFrontActivity());
                }
            }
            ToastUtils.showShort("登录已过期，请重新登录");
        } else if (e instanceof UnknownHostException || e instanceof ConnectException || e instanceof HttpException) {
//            ToastUtils.showToast(MyApplication.context, "连接失败");
        } else if (e instanceof JsonSyntaxException) {
            //
        } else if (e instanceof IOException && errorMsg != null && errorMsg.contains("429")) {
            //
        } else if (!TextUtils.isEmpty(errorMsg)) {
            ToastUtils.showShort(errorMsg);
        }
    }


    /**
     * 请求成功
     *
     * @param response 服务器返回的数据
     */
    abstract public void onSuccess(T response);

}
